package Service.Impl;

import Dao.StaffDao;
import Model.Staff;
import Model.StaffChanged;
import Service.StaffService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import utils.Excel;
import utils.ReturnDataForLayui;
import utils.ReturnData;
import utils.UpdateOrInsertResultDeal;



import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;


import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.*;


@Service("StaffService")
public class StaffServiceImpl implements StaffService {

    @Autowired
    private StaffDao staffDao;
//查询所有护工信息
    @Override
    public List<Staff> getAllStaffList(){
        System.out.println("service层：执行查询");
        return staffDao.getAllStaffList();
    }
//查询所有护工变更信息
    @Override
    public List<StaffChanged> getAllStaffChangedList(){
        System.out.println("service层：执行查询");
        return staffDao.getAllStaffChangedList();
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=30000,rollbackFor={RuntimeException.class, Exception.class})
    public String delStaff(int id) {
        //1.删除角色对应的权限
        //batchDelRolePerms(id);
        //2.删除角色
        System.out.println("service层：执行删除");
        Staff staffInfobyID=staffDao.findStaffInfobyID(id);
        Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());
        System.out.println("机构代码："+staffInfobyID.getSettlement_code());
        staffInfobyID.setHistory_change_time(timestamp);
        //staff.setHistory_change_time(timestamp);
        System.out.println("修改时间11："+staffInfobyID.getHistory_change_time());
        //System.out.println("修改时间22："+staff.getHistory_change_time());
        //System.out.println("staff："+staff);
        int a=staffDao.RecordDel(staffInfobyID);

        int num=this.staffDao.deleteByPrimaryKey(id);
        if(num<1){
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "操作失败";
        }
        return "ok";
    }

//    搜索-信息页面
    @Override
    public List<Staff> findStaffInfo(String StaffName,String StaffYbid,String StaffSbdw,String StaffZylevel,List<String> StaffStatus) {
        System.out.println("service层："+StaffName);
        System.out.println("service层："+StaffYbid);
        System.out.println("service层："+StaffSbdw);
        System.out.println("service层："+StaffZylevel);
        System.out.println("service层："+StaffStatus);
        System.out.println("service层：进入dao层");
        return staffDao.findStaffInfo(StaffName,StaffYbid,StaffSbdw,StaffZylevel,StaffStatus);
    }

    //    根据ID查询
    @Override
    public Staff findStaffInfobyID(Integer id){
        return staffDao.findStaffInfobyID(id);
    }

    //  搜索-变更页面
    @Override
    public List<StaffChanged> findStaffChangedInfo(String nameSearch,String ybidSearch,String titleSearch){
        System.out.println("service层："+nameSearch);
        System.out.println("service层："+ybidSearch);
        System.out.println("service层："+titleSearch);
        System.out.println("service层：进入dao层");
        return staffDao.findStaffChangedInfo(nameSearch,ybidSearch,titleSearch);
    }

    //    更新页面
    @Override
    public String updateNursing(Staff staff,String settleCode,HttpSession session){
        System.out.println("service层:"+staff.getYbid());
        System.out.println("service层"+staff.getName());
        if (staff.getId() != null) {
            if(staff.getYbid().length()==6){
                System.out.println("service层:医保ID校验位数正确："+staff.getYbid());
                //            根据ID找到修改前的数据
                Staff staffInfobyID=staffDao.findStaffInfobyID(staff.getId());
                System.out.println("service层:staff："+staff.getId());
                System.out.println("service层:存在此护工");
//            记录修改时间
                Date date = new Date();
                Timestamp timestamp = new Timestamp(date.getTime());
                staffInfobyID.setHistory_change_time(timestamp);
                staff.setHistory_change_time(timestamp);
                System.out.println("修改时间11："+staffInfobyID.getHistory_change_time());
                System.out.println("修改时间22："+staff.getHistory_change_time());
                System.out.println("staff："+staff);

//            修改前的数据
                Map<String,Object> oldStaff = new HashMap<String,Object>();
                oldStaff.put("sbdw", staffInfobyID.getSbdw());
                oldStaff.put("sbdwcode",staffInfobyID.getSbdwcode());
                oldStaff.put("ybid",staffInfobyID.getYbid());
                oldStaff.put("rylb",staffInfobyID.getRylb());
                oldStaff.put("name", staffInfobyID.getName());
                oldStaff.put("gender",staffInfobyID.getGender());
                oldStaff.put("id_number",staffInfobyID.getId_number());
                oldStaff.put("zylevel", staffInfobyID.getZylevel());
                oldStaff.put("phone_number",staffInfobyID.getPhone_number());
                oldStaff.put("certificate_code",staffInfobyID.getCertificate_code());
                oldStaff.put("fzrq",staffInfobyID.getFzrq());
                oldStaff.put("ybbsmrq",staffInfobyID.getYbbsmrq());
                oldStaff.put("fservdate",staffInfobyID.getFservdate());
                oldStaff.put("worklength",staffInfobyID.getWorklength());
                oldStaff.put("status",staffInfobyID.getStatus());
                oldStaff.put("lastserv_org",staffInfobyID.getLastserv_org());
                oldStaff.put("history_change_time",staffInfobyID.getHistory_change_time());
                oldStaff.put("serv_org",staffInfobyID.getServ_org());
                System.out.println("service层:旧的数据：oldStaff："+oldStaff);

//            修改后的数据
                Map<String,Object> newStaff = new HashMap<String,Object>();
                newStaff.put("sbdw", staff.getSbdw());
                newStaff.put("sbdwcode",staff.getSbdwcode());
                newStaff.put("ybid",staff.getYbid());
                newStaff.put("rylb",staff.getRylb());
                newStaff.put("name", staff.getName());
                newStaff.put("gender",staff.getGender());
                newStaff.put("id_number",staff.getId_number());
                newStaff.put("zylevel", staff.getZylevel());
                newStaff.put("phone_number",staff.getPhone_number());
                newStaff.put("certificate_code",staff.getCertificate_code());
                newStaff.put("fzrq",staff.getFzrq());
                newStaff.put("ybbsmrq",staff.getYbbsmrq());
                newStaff.put("fservdate",staff.getFservdate());
                newStaff.put("worklength",staff.getWorklength());
                newStaff.put("status",staff.getStatus());
                newStaff.put("lastserv_org",staff.getLastserv_org());
                newStaff.put("history_change_time",staff.getHistory_change_time());
                newStaff.put("serv_org",staff.getServ_org());
                System.out.println("service层:新的数据：newStaff："+newStaff);

//              比较新旧数据
                for(Map.Entry<String,Object>entry:oldStaff.entrySet()){
//                获取当前键值
                    String keyContent=entry.getKey();
                    System.out.println("获取的key值："+keyContent);
//                获取当前键值的value值（新+旧）
                    Object oldValue=entry.getValue() ==null?"":entry.getValue();
                    Object newValue=newStaff.get(entry.getKey())==null?"":newStaff.get(entry.getKey());
                    System.out.println("比较循环前的数据（旧）："+oldValue);
                    System.out.println("比较循环前的数据（新）："+newValue);
//                比较：如果二者value不同
                    if(!oldValue.equals(newValue)){
                        System.out.println("不同的数据（旧）："+oldValue);
                        System.out.println("不同的数据（新）："+newValue);
                        System.out.println("不同");
//                    建表
                        Map<String,Object> insertInfo = new HashMap<String,Object>();
//                        判断变更字段
                        switch (keyContent){
                            case "sbdw": insertInfo.put("changed_title","申报单位");break;
                            case "sbdwcode": insertInfo.put("changed_title","申报单位机构代码");break;
                            case "ybid":insertInfo.put("changed_title","医保ID");break;
                            case "rylb":insertInfo.put("changed_title","人员类别");break;
                            case "name":insertInfo.put("changed_title","姓名");break;
                            case "gender":insertInfo.put("changed_title","性别");break;
                            case "id_number":insertInfo.put("changed_title","身份证号");break;
                            case "zylevel":insertInfo.put("changed_title","职业等级");break;
                            case "phone_number":insertInfo.put("changed_title","联系电话");break;
                            case "certificate_code":insertInfo.put("changed_title","证书编号");break;
                            case "fzrq":insertInfo.put("changed_title","发证日期");break;
                            case "ybbsmrq":insertInfo.put("changed_title","获得医保标识码日期");break;
                            case "fservdate":insertInfo.put("changed_title","首次服务日期");break;
                            case "worklength":insertInfo.put("changed_title","工作年限");break;
                            case "status":insertInfo.put("changed_title","人员状态");break;
                            case "lastserv_org":insertInfo.put("changed_title","上一家护理机构");break;
                            case "serv_org":insertInfo.put("changed_title","护理机构");break;
                        }
                        System.out.println("启变日期："+staff.getStart_change_date());
                        insertInfo.put("name", staff.getName());
                        insertInfo.put("ybid", staff.getYbid());
                        insertInfo.put("history_change_time", staff.getHistory_change_time());
                        insertInfo.put("start_change_date",staff.getStart_change_date());
                        insertInfo.put("new_content", newValue);
                        insertInfo.put("history_content", oldValue);
                        insertInfo.put("settlement_code",settleCode);
                        System.out.println("变更后的表："+insertInfo);
                        System.out.println("进入dao层：InsertHistoryChange");
//                    以哈希表形式传入更改后的数据
                        this.staffDao.InsertHistoryChange(insertInfo);
                    }else{
//                    若value相同，则不传
                        System.out.println("相同的数据（旧）："+oldValue);
                        System.out.println("相同的数据（新）："+newValue);
                        System.out.println("相同");
                    }
                }
//            更新数据
                this.staffDao.updateById(staff);
                System.out.println("update成功（Impl）");
            }else{
                System.out.println("校验失败：医保ID的长度为："+staff.getYbid().length());
                return "errorYbid";
            }
        }
        return "ok";
    }

    @Transactional(propagation = Propagation.REQUIRED,readOnly = true)
    @Override
    public ReturnDataForLayui getList(Staff staff) {
        PageHelper.startPage(staff.getPage(),staff.getLimit());
        List<Staff> list = staffDao.getList(staff);
        PageInfo<Staff> info = new PageInfo<>(list);
        return ReturnDataForLayui.success(list,info.getTotal());
    }

    @Transactional(propagation = Propagation.REQUIRED,readOnly = true)
    @Override
    public ReturnDataForLayui getList2(Staff staff) {
        PageHelper.startPage(staff.getPage(),staff.getLimit());
        List<Staff> list = staffDao.getList2(staff);
        PageInfo<Staff> info = new PageInfo<>(list);
        return ReturnDataForLayui.success(list,info.getTotal());
    }
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public ReturnData updatePhone(Staff staff) {
        int i = staffDao.updatePhone(staff);
        return UpdateOrInsertResultDeal.dealWith(i);
    }

    //  传入excel
    @Override
    public String InputExcel(InputStream is, String originalFilename,String settleCode) {
        System.out.println("service层：传入excel文件");
        Map<String,Map<String,Object>> param = new HashMap<String,Map<String,Object>>();
        Map<String,Object> ginsengMap = new HashMap<String,Object>();
        List<ArrayList<Object>> list;
        if (originalFilename.endsWith(".xls")) {
            System.out.println("service层：是2003版的excel");
            list = Excel.readExcel2003(is);
        } else {
            System.out.println("service层：是2007版的excel");
            list = Excel.readExcel2007(is);
        }
        for (int i=0,j=list.size();i<j;i++){
            List<Object> row = list.get(i);
            System.out.println("service层：当前i= "+i);
            System.out.println("service层：当前row= "+row);
            System.out.println("service层：判断人员状态： "+row.get(14).toString());
            if(row.get(14).toString().equals("无效转出")){
                System.out.println("service层：人员状态确定为无效转出");
//                ginsengMap.put("id", row.get(0).toString());
                ginsengMap.put("ybid", row.get(1).toString());
                ginsengMap.put("rylb", row.get(2).toString());
                ginsengMap.put("name", row.get(3).toString());
                ginsengMap.put("gender", row.get(4).toString());
                ginsengMap.put("id_number", row.get(5).toString());
                ginsengMap.put("zylevel", row.get(6).toString());
                ginsengMap.put("phone_number", row.get(7).toString());
                ginsengMap.put("sbdw", row.get(8).toString());
                ginsengMap.put("sbdwcode", row.get(9).toString());
                ginsengMap.put("fzrq", row.get(10).toString());
                ginsengMap.put("ybbsmrq", row.get(11).toString());
                ginsengMap.put("fservdate", row.get(12).toString());
                ginsengMap.put("worklength", row.get(13).toString());
                ginsengMap.put("status", row.get(14).toString());
                ginsengMap.put("serv_org", row.get(15).toString());
                ginsengMap.put("lastserv_org", row.get(16).toString());
                ginsengMap.put("certificate_code", row.get(17).toString());
                ginsengMap.put("settlement_code",settleCode);
                param.put("keys", ginsengMap);
                System.out.println("service层：进入dao层");
                staffDao.InputExcel(param);
                System.out.println("service层：inputExcel成功");
            }
            else{
                System.out.println("service层：人员状态非无效转出");
            }
        }
        return "01";
    }

    @Override
//  制定派工日程页面：查找是否存在该护工
    public List<Staff> searchStaffbyYbid(String StaffYbid){
        System.out.println("service层：查找护工："+StaffYbid);
        return staffDao.searchStaffbyYbid(StaffYbid);
    }

    @Override
    public List<Staff> searchArrangeNursing(String NursingName,String NursingYbid,String NursingID){
        System.out.println("service层：查找护工："+NursingName);
        return staffDao.searchArrangeNursing(NursingName,NursingYbid,NursingID);
    }

    /**
     * 获取护工的ID和name字段
     */
    @Override
    public List<Staff> getHgIdName(){
        List<Staff> list = staffDao.getHgIdName();
        System.out.println("[service层，获取到护工的ID和name：]"+list);
        return list;
    }

    /**
     * 根据机构查找护工姓名
     * @param settlement_code
     * @return
     */
    @Override
    public List<Staff> getHgNameByCode(String settlement_code){
        List<Staff> list = staffDao.getHgNameByCode(settlement_code);
        System.out.println("[service层，获取到护工的姓名！]"+list);
        return list;
    }

    /**
     * 根据姓名查找护工身份证号
     * @param name
     * @return
     */
    @Override
    public List<Staff> getHgIdNumberByName(String name){
        List<Staff> list = staffDao.getHgIdNumberByName(name);
        System.out.println("[service层，获取到护工的身份证号！]"+list);
        return list;
    }

    /**
     * 更新护工的设备（发放设备后添加）
     */

    @Override
    public void updateHgDevice(Staff staff){
        staffDao.updateHgDevice(staff);
        System.out.println("service层：更新护工的设备（发放后添加）！");
    }

    @Override
    public String wechatRegisterStaff(String StaffID,String StaffYbid,String StaffPassword){
        System.out.println("service层：护工ID："+StaffID);
        System.out.println("service层：护工医保ID："+StaffYbid);
        System.out.println("service层：护工密码："+StaffPassword);
        List<Staff> staff=this.staffDao.searchStaffbyYbid(StaffYbid);
        if(staff.size()!=0){
            System.out.println("找到该护工");
            String ID=this.staffDao.wechatGetIDbyYbid(StaffYbid);//根据医保卡号返回身份证号
            String ExistPassword=this.staffDao.wechatGetPasswordbyYbid(StaffYbid);//根据医保卡号查看是否已有密码
            if(ID.equals(StaffID)){
                System.out.println("身份信息填写正确");
                if(ExistPassword==""||ExistPassword==null){
                    this.staffDao.wechatInsertPassword(StaffYbid,StaffPassword);
                    return "SuccessRegister";
                }else{
                    System.out.println("已注册过");
                    return "AlreadyExist";
                }
            }else{
                System.out.println("医保卡号和身份证不匹配");
                return "Incompatible";
            }
        }else{
            System.out.println("医保卡号填错");
            return "errorYbid";
        }
    }

    //     护工页面添加权限：根据机构结算代码找到相应护工
    @Override
    public List<Staff> getStaffbySettleCode(String settleCode){
        System.out.println("机构结算代码："+settleCode);
        return this.staffDao.getStaffbySettleCode(settleCode);
    }
//  护工页面：历史变更记录查看，根据机构结算代码
    @Override
    public List<StaffChanged> getStaffChangedsbySettleCode(String settleCode){
        System.out.println("机构结算代码："+settleCode);
        return this.staffDao.getStaffChangedsbySettleCode(settleCode);
    }

//    护工页面添加权限：查找机构的护工
    @Override
    public List<Staff> findStaffInfobySettleCode(String settleCode,String StaffName,String StaffYbid,
                                          String StaffSbdw,String StaffZylevel,List<String> StaffStatus){
        return staffDao.findStaffInfobySettleCode(settleCode,StaffName,StaffYbid,StaffSbdw,StaffZylevel,StaffStatus);
    }


//     * 护工页面添加权限：搜索历史变更
    @Override
    public List<StaffChanged> findStaffChangedInfobySettleCode(String nameSearch,String ybidSearch,String titleSearch,String settleCode){
        return staffDao.findStaffChangedInfobySettleCode(nameSearch,ybidSearch,titleSearch,settleCode);
    }


//     * 派工日程安排页面：权限：搜索护工
    @Override
    public List<Staff> searchArrangeNursingbySettelCode(String NursingName,String NursingYbid,String NursingID,String SettleCode){
        return staffDao.searchArrangeNursingbySettelCode(NursingName,NursingYbid,NursingID,SettleCode);
    }

    @Override
    public List<Staff> getDeviceByOpenId(Staff staff) {
        return staffDao.getDeviceByOpenId(staff);
    }
}
